package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.gson.JsonObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishMapper;
import com.sky.mapper.FlavorMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class DishServiceImpl implements DishService {

    @Autowired
    DishMapper dishMapper;
    @Autowired
    FlavorMapper flavorMapper;
    @Autowired
    SetmealDishMapper setmealDishMapper;
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    private static final String CATEGORY_PREFIX = "category:";

    /**
     * 新增菜品，同时新增口味
     * @param dishDTO
     */
    @Transactional
    public void saveWithFlavor(DishDTO dishDTO) {
        //将菜品存储到数据库
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.insert(dish);

        //取出生成的id作为flavor的dishId(在mapper映射文件中配置属性，让插入数据后将id注入对象)
        long dishId = dish.getId();
        List<DishFlavor> flavors = dishDTO.getFlavors();

        if(flavors == null || flavors.isEmpty()) return;
        //为所有口味设置dishId
        flavors.forEach(flavor ->{
            flavor.setDishId(dishId);
        });

        //将所有flavor存储到数据库
        flavorMapper.insertBatch(flavors);
    }

    /**
     * 菜品分页查询
     * @param dto
     * @return
     */
    public PageResult pageQuery(DishPageQueryDTO dto) {
        PageHelper.startPage(dto.getPage(),dto.getPageSize());
        Page<DishVO> page = dishMapper.selectPage(dto);
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 删除菜品
     * @param ids
     */
    @Transactional
    public void deleteBatch(String ids) {
        //如果菜品在出售中，那么不能删除
        //查询id在列表中并且status为出售的菜品数量若数量大于0，则不能删除
        //ids以逗号分隔，此处要做in操作，直接加上括号插入sql
        int dishCount = dishMapper.selectCountOnSellByIds(ids);
        if(dishCount>0)
            throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);

        //如果菜品被某个套餐包含，则不能删除，故根据dishId查询setmeal_dish表，若条数大于0则不能删除
        int setmealDishCount = setmealDishMapper.selectCountByDishIds(ids);
        if(setmealDishCount>0)
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);

        //删除菜品
        dishMapper.deleteByIds(ids);
        //删除相关联的口味标签
        flavorMapper.deleteByDishIds(ids);
    }

    /**
     * 根据id查询菜品
     *
     * @param id
     * @return
     */
    public DishVO getOne(Long id) {
        Dish dish = dishMapper.selectById(id);
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);

        //找出所有口味存储到属性中
        List<DishFlavor> flavors = flavorMapper.selectListByDishId(id);
        dishVO.setFlavors(flavors);
        return dishVO;
    }

    /**
     * 根据id更新菜品信息
     * @param dishDTO
     */
    @Transactional
    public void update(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.update(dish);

        //把原有口味全部删除，并将此次提交的口味插入数据库
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if(flavors == null || flavors.isEmpty()) return;
        flavors.forEach(flavor ->{
            flavor.setDishId(dish.getId());
        });
        flavorMapper.deleteByDishIds(dish.getId().toString());
        flavorMapper.insertBatch(flavors);
    }

    /**
     * 起售或停售菜品
     * @param id
     * @param status
     */
    public void startOrStop(Long id, int status) {
        Dish dish = Dish.builder()
                .id(id)
                .status(status)
                .build();
        dishMapper.update(dish);
    }


    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        //从redis中查询数据
        String key = CATEGORY_PREFIX + dish.getCategoryId();
        String jsonString = stringRedisTemplate.opsForValue().get(key);
        List<DishVO> dishVOList = JSON.parseArray(jsonString, DishVO.class);
        //若有则直接返回
        if(dishVOList != null && !dishVOList.isEmpty()) {
            return dishVOList;
        }

        //从数据库中查询
        List<Dish> dishList = dishMapper.list(dish);

        dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = flavorMapper.selectListByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        //将数据存入缓存
        stringRedisTemplate.opsForValue().set(key, JSON.toJSONString(dishVOList));

        return dishVOList;
    }
}
